package com.loren.demo19.lock;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
@AllArgsConstructor
public class RedisLock {

    private final StringRedisTemplate stringRedisTemplate;

    public boolean lock(String key, String value, long expire, TimeUnit timeUnit) {
        Boolean flag = this.stringRedisTemplate.opsForValue().setIfAbsent(key, value, expire, timeUnit);
        if (flag == null || !flag) {
            log.debug("get lock fail");
            return false;
        }
        log.debug("get lock success");
        return true;
    }

    public void unLock(String key, String value) {
        String script = "if redis.call('get', KEYS[1]) == KEYS[2] then return redis.call('del', KEYS[1]) else return 0 end";
        RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
        Long result = this.stringRedisTemplate.execute(redisScript, Arrays.asList(key, value));
        if (result == null || result == 0) {
            log.debug("unlock fail");
        } else {
            log.debug("unlock success");
        }
    }
}
